﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
#if MicrosoftOwin
using Microsoft.Owin.Builder;
#endif

namespace WebApplication1
{
    using AppFunc = Func<IDictionary<string, object>, Task>;
    /// <summary>
    /// 针对Microsoft.Owin的JWS开放接口适配器
    /// <para>本接口适合兼容Microsoft.Owin规范的应用</para>
    /// </summary>
    public class Adapter
    {
        static AppFunc _owinApp;
        /// <summary>
        /// 默认构造函数
        /// </summary>
        public Adapter()
        {
#if MicrosoftOwin
            // 创建默认的AppBuilder
            Microsoft.Owin.Builder.AppBuilder builder = new Microsoft.Owin.Builder.AppBuilder();
            // 实例化 Startup类
            // 这个类中必须有“Configuration”方法
            var startup = new Startup();
            // 调用Startup类的Configuration方法，把自己的处理函数注册到处理流程中
            startup.Configuration(builder);
            // 生成OWIN“入口”函数
            _owinApp = builder.Build();
#endif
#if NFinalOwin
            NFinal.NFinalOwinMiddleware middle = new NFinal.NFinalOwinMiddleware(new NFinal.Owin.Builder.Completed().Invoke);
            _owinApp = middle.Invoke;
#endif
        }
        /// <summary>
        /// *** JWS所需要的关键函数 ***
        /// <para>每个请求到来，JWS都会把请求打包成字典，调用这个函数</para>
        /// </summary>
        /// <param name="env">新请求的环境字典，具体内容参见OWIN标准</param>
        /// <returns>返回一个正在运行或已经完成的任务</returns>
        public Task OwinMain(IDictionary<string, object> env)
        {
            //如果为空
            if (_owinApp == null) return null;
            //将请求交给Microsoft.Owin处理
            return _owinApp(env);
        }


    } //end class
}